package com.softeem.xyblogmaster.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.softeem.xyblogmaster.controller.AuthController;
import com.softeem.xyblogmaster.domain.Users;
import com.softeem.xyblogmaster.exception.ServiceException;
import com.softeem.xyblogmaster.mapper.UsersMapper;
import com.softeem.xyblogmaster.service.AuthService;
import com.softeem.xyblogmaster.util.Md5Util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UsersMapper usersMapper;

    @Value("${md5.salt}")
    private String salt;

    @Override
    public Users doLogin(Users users) {
        LambdaQueryWrapper<Users> lambdaQueryWrapper=new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Users::getUname,users.getUname());
        List<Users> userslist = usersMapper.selectList(lambdaQueryWrapper);
        if(userslist!=null&&userslist.size()>0){
            Users u=userslist.get(0);
            //一般来说我们的数据表里面的密码字段都是密文
            String md5= Md5Util.md5(users.getUpwd(),salt);
            //比较应该是密文=加密(传递密码)
            if(u.getUpwd().equals(md5)){
                return u;
            }
            else{
                throw  new ServiceException("403-用户名或者密码错误");
            }
        }
        else{
            throw new ServiceException("401-没有这个用户");
        }
    }

    @Transactional
    public boolean doRegister(Users users) {
        LambdaQueryWrapper<Users> lambdaQueryWrapper=new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Users::getUname,users.getUname());
        List<Users> userslist = usersMapper.selectList(lambdaQueryWrapper);
        if(userslist!=null&&userslist.size()>0){
            throw new ServiceException("405-用户已存在");
        }
        else {
            String password = users.getUpwd();
            users.setUpwd(Md5Util.md5(password, salt));
            users.setIsAdmin(0); //普通用户
            usersMapper.insertOrUpdate(users);
            return true;
        }
    }


}
